<template>
  <view :style="'background-color: #fff;overflow:auto;height:' + height + 'px'">
    <van-nav-bar
      :border="false"
      custom-class="myNavbar"
      style="font-size: 30rpx"
      :safeAreaInsetTop="false"
      title="账单"
    />

    <view class="detailCard">
      <van-row gutter="20">
        <van-col span="11">
          <div @click="showPopup" style="font-size: 40rpx">
            {{ year }}年{{ month }}月
            <van-icon name="arrow-down" style="margin-left: 5px" />
          </div>
        </van-col>
        <van-col span="6" style="font-size: 35rpx">收入</van-col>
        <van-col span="5" style="font-size: 35rpx">支出</van-col>
      </van-row>
      <van-row gutter="20">
        <van-col
          span="11"
          style="font-size: 50rpx; letter-spacing: 2rpx; line-height: 50px"
          >{{ available }}</van-col
        >
        <van-col span="6" style="font-size: 35rpx; line-height: 50px">{{
          inSum
        }}</van-col>
        <van-col span="5" style="font-size: 35rpx; line-height: 50px">{{
          outSum
        }}</van-col>
      </van-row>
    </view>

    <view v-if="accountList.length == 0"> </view>

    <van-cell-group v-else>
      <view v-for="(day, i) in accountList" :key="i">
        <van-cell>
          <span slot="title">
            <view
              class="van-cell-text"
              style="height: 35rpx; font-size: 12px; margin-top: 1rpx"
            >
              {{ dateShow(day) }}
            </view>
          </span>
        </van-cell>
        <van-swipe-cell right-width="45" v-for="(record, j) in day" :key="j">
          <van-cell
            center
            :title="record.a_type"
            :value="getMoney(record)"
            :label="record.a_comment"
          >
            <image
              @click="showPopupUpdate(record)"
              slot="icon"
              :src="icon.edit"
              mode="aspectFit"
              style="width: 30px; height: 17px; margin-right: 14px"
            />
          </van-cell>

          <view slot="right" align="center" style="padding-top: 20%">
            <image
              @click="deleteRecord(record, i, j)"
              slot="icon"
              :src="icon.delete"
              mode="aspectFit"
              style="width: 40px; height: 25px"
            />
          </view>
        </van-swipe-cell>
      </view>
    </van-cell-group>

    <!-- <van-dialog :show="detele" id="van-dialog" /> -->

    <van-popup
      :show="popupShow"
      position="bottom"
      custom-style="height: 60%;"
      @close="popupClose"
    >
      <van-datetime-picker
        style="height: 300px"
        type="year-month"
        :value="currentDate"
        :min-date="minDate"
        @cancel="popupClose"
        @confirm="update"
        @change="dateTimeChange"
      />
    </van-popup>

    <van-popup
      :show="popupShowUpdate"
      position="bottom"
      custom-style="height: 80%;"
      @close="popupCloseUpdate"
    >
      <van-collapse accordion :value="activeName" @change="onChangeCollapse">
        <van-collapse-item title="类型" name="1" :value="type">
          <van-picker :columns="columns" @change="onChangePicker" />
        </van-collapse-item>

        <van-collapse-item title="日期" name="2" :value="dateForShow">
          <van-datetime-picker
            :show-toolbar="false"
            :value="currentDate"
            type="date"
            :min-date="minDate"
            :max-date="maxDate"
            @input="onInputDate"
          />
        </van-collapse-item>
      </van-collapse>

      <van-field
        label="金额"
        :value="money"
        input-align="right"
        @input="showMoney"
      />
      <van-field
        label="备注"
        :value="comment"
        input-align="right"
        @input="showComment"
      />
      <view style="padding-top: 50rpx">
        <van-button
          color="#ffc0cb"
          size="small"
          style="margin-left: 300rpx"
          @click="preserveUpdate"
        >
          确定
        </van-button>
      </view>
      {{ money }}
    </van-popup>
  </view>
</template>

<script>
const types = {
  收入: ['工资', '生活费', '兼职', '其它'],
  支出: ['购物', '娱乐', '交通', '餐饮', '其它'],
};
export default {
  props: ['height'],
  data() {
    return {
      minDate: new Date(2010, 1, 1).getTime(),
      maxDate: new Date(2050, 1, 1).getTime(),
      currentDate: new Date().getTime(),
      popupShow: false,
      popupShowUpdate: false,
      inSum: 0.0,
      outSum: 0.0,
      available: 0.0,
      accountList: [],
      year: 0,
      month: 0,
      type: '其它',
      inout: true,
      money: '',
      comment: '',
      record: {},
      date: new Date(),
      dateForShow: '',
      id: '',

      columns: [
        {
          values: Object.keys(types),
          className: 'column1',
        },
        {
          values: types['收入'],
          className: 'column2',
          defaultIndex: 2,
        },
      ],

      icon: {
        edit: '/static/account/edit_0.png',
        delete: '/static/account/delete_0.png',
      },
      activeName: '',
      minDate: new Date(2010, 1, 1).getTime(),
      maxDate: new Date(2050, 1, 1).getTime(),
      currentDate: new Date().getTime(),
    };
  },
  methods: {
    dateShow(dateArr) {
      var date = new Date(dateArr[0].a_date);
      var month1 = date.getMonth() + 1;

      return month1 + '月' + date.getDate() + '日';
    },
    getMoney(record) {
      if (record.a_inout == true) return '-' + record.a_money;
      else return '+' + record.a_money;
    },
    async deleteRecord(record, dayIndex, itemIndex) {
      this.id = record._id;
      uni.showToast({
        title: '删除成功',
        duration: 1000,
      });
      const res = await this.lynRequest.run('deleteAccount', {
        _id: this.id,
      });
      if (this.accountList[dayIndex].length == 1) {
        this.accountList.splice(dayIndex, 1);
      } else {
        this.accountList[dayIndex].splice(itemIndex, 1);
      }
    },
    // async sureDeleteRecord(record) {
    //   this.id = record._id;
    //   const res = await this.lynRequest.run("deleteAccount", {
    //     _id: this.id,
    //   });
    // },
    showPopup() {
      this.popupShow = true;
    },
    popupClose() {
      this.popupShow = false;
    },
    showPopupUpdate(record) {
      console.log(record);
      this.record = record;
      this.type = record.a_type;
      this.comment = record.a_comment;
      this.inout = record.a_inout;
      this.money = Number(record.a_money);
      this.id = record._id;
      this.popupShowUpdate = true;
    },
    popupCloseUpdate() {
      this.popupShowUpdate = false;
    },

    onClickLeft() {
      console.log('返回主界面');
    },
    onClickRight() {
      console.log('确定');
    },
    showDate() {
      var year = this.date.getFullYear();
      var month = this.date.getMonth() + 1;
      var day = this.date.getDate();
      this.dateForShow = year + '-' + month + '-' + day;
    },

    onChangeCollapse(event) {
      this.activeName = event.detail;
      console.log(event);
    },

    onChangePicker(event) {
      const { picker, value, index } = event.detail;
      picker.setColumnValues(1, types[value[0]]);
    },
    onInputDate(event) {
      this.currentDate = event.detail;
    },
    async preserveUpdate() {
      console.log(this.money);
      console.log(this.comment);
      console.log(this.type);
      console.log(this.date);
      console.log(this.inout);

      const res = await this.lynRequest.run('updateAccount', {
        a_type: this.type,
        a_inout: this.inout,
        a_money: this.money,
        a_comment: this.comment,
        a_date: this.date,
        _id: this.id,
      });
      this.record.a_money = this.money;
      this.record.a_comment = this.comment;
      this.record.a_type = this.type;

      uni.showToast({
        title: '修改成功',
        duration: 2000,
      });

      console.log(res);
    },
    showMoney(event) {
      this.money = event.detail;
    },
    showComment(event) {
      this.comment = event.detail;
    },
    onChangeCollapse(event) {
      this.activeName = event.detail;
      console.log(event);
    },

    onInputDate(event) {
      this.currentDate = event.detail;
      console.log(event);
      this.date = new Date(event.detail);
      this.showDate();
      console.log(this.date);
    },

    onChangePicker(event) {
      console.log(event);
      const { picker, value, index } = event.detail;
      picker.setColumnValues(1, types[value[0]]);
      console.log(types);
      console.log(value);

      var inout = value[0];
      if (inout == '收入') this.inout = false;
      else this.inout = true;
      console.log(this.inout);
      this.type = value[1];
    },

    dateTimeChange(event) {
      this.year = Number(event.detail.getColumnValue(0));

      this.month = Number(event.detail.getColumnValue(1));

      console.log(this.year);
      console.log(event.detail.getColumnValue(1));
    },
    update() {
      this.popupShow = false;
      this.getDetail(this.year, this.month - 1);
    },

    async getDetail(year, month) {
      console.log(year, month);
      const res = await this.lynRequest.run('queryAccount', {
        year: year,
        month: month,
      });
      var accountList = res.accountList;
      //var inSum = res.inSum[0] == undefined ? 0.0 : res.inSum[0].moneyinSum;
      this.inSum = 0;
      this.outSum = 0;
      this.available = 0;
      for (var i = 0; i < accountList.length; i++) {
        if (accountList[i].a_inout == false) {
          this.inSum += Number(accountList[i].a_money);
        } else {
          this.outSum += Number(accountList[i].a_money);
        }
      }
      console.log(this.inSum);

      //var outSum = res.outSum[0] == undefined ? 0.0 : res.outSum[0].moneyoutSum;
      this.available = this.inSum - this.outSum;
      this.inSum = this.inSum.toFixed(2);
      this.outSum = this.outSum.toFixed(2);
      this.available = this.available.toFixed(2);

      // const inSum = res.inSum[0] == undefined ? 0.0 : res.inSum[0].moneyinSum;
      // this.inSum = inSum.toFixed(2);
      // const outSum =
      //   res.outSum[0] == undefined ? 0.0 : res.outSum[0].moneyoutSum;
      // this.outSum = outSum.toFixed(2);
      // const available = res.available;
      // this.available = available.toFixed(2);
      console.log(res);

      var accountList = res.accountList;
      accountList.sort((a, b) => {
        return a.a_date.localeCompare(b.a_date);
      });
      var accountListtwo = [[]];
      if (accountList.length == 0) {
        this.accountList = [];
        return;
      }

      var index = 0;
      var time0 = new Date(accountList[0].a_date).getDate();

      console.log(accountList);

      accountList.forEach((item) => {
        var day = new Date(item.a_date).getDate();
        if (day == time0) {
          accountListtwo[index].push(item);
        } else {
          accountListtwo.push([]);
          index++;
          accountListtwo[index].push(item);
          time0 = day;
        }
        console.log(time0);
      });
      this.accountList = accountListtwo;
      console.log(this.accountList);
    },
  },
  async created() {
    var date = new Date();
    console.log(date);
    this.year = date.getFullYear();
    this.month = date.getMonth() + 1;
    await this.getDetail(this.year, this.month - 1);

    // const res = await this.lynRequest.run("getUserInfo");
    // console.log(res);
  },
};
</script>

<style></style>

<style scoped>
.detailCard {
  margin: auto;
  margin-top: 16px;
  margin-bottom: 16px;
  width: 650rpx;
  background-color: #ffe4e1;
  box-shadow: 0 0 4px 5px #ffe4e1;
  height: 200rpx;
  border-radius: 8px;
  padding-left: 30rpx;
  padding-top: 60rpx;
}
</style>
